package com.puck;

import com.db.DBUtil;

import java.sql.Timestamp;
import java.sql.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

public class test {
    public static void main(String[] args) throws Exception {
        Connection conn = DBUtil.getConnection();
        String game_winner_ID;
        System.out.println("*************用户菜单*************");

        while (true) {
            System.out.println("请选择1.登录 2.注册 3.注销某个账户");
            Scanner scanner = new Scanner(System.in);
            int chooice = scanner.nextInt();
            if (chooice == 1) {
                LogIn.denglu();
                break;
            } else if (chooice == 2) {
                LogIn.zhuce();
                System.out.println("注册成功！\n请登录：");
                LogIn.denglu();
                break;
            } else if (chooice == 3) {
                LogIn.zhuxiao();
            } else System.out.println("请输入正确的指令");
        }
        while (true) {
            System.out.println("游戏开始");
            Date begin_time = new Date();
            Timestamp timeStamp1 = new Timestamp(begin_time.getTime());
            Thread.sleep(2000);
            System.out.println("开始时间：" + timeStamp1);
            Thread.sleep(2000);
            System.out.println("开始创建扑克牌");
            Thread.sleep(2000);
            List<Puke> pukes = new ArrayList<>();//创建扑克牌列表
            for (String dot : Compare.DOTS) {
                for (Type type : Compare.TYPE) {
                    pukes.add(new Puke(dot, type));//向扑克列表中添加所有的扑克牌
                }
            }
            System.out.println("扑克牌列表：");
            Thread.sleep(2000);
            for (Puke puke : pukes) {
                Thread.sleep(200);
                System.out.print(puke.getType().getCol() + puke.getDot() + " ");
            }
            Thread.sleep(500);
            System.out.println("开始导入您的账号信息,您将与电脑用户wang对战");
            Thread.sleep(2000);
            List<Player> players = new ArrayList<>();//创建玩家列表
            for (int i = 1; i < 3; i++) {
                if (i == 1) players.add(new Player(LogIn.getUsername()));//向玩家列表中添加玩家
                if (i == 2) players.add(new Player("wang"));
            }
            System.out.println("开始洗牌");
            Thread.sleep(2000);
            Collections.shuffle(pukes);//打乱扑克牌顺序
            System.out.println("洗牌结束，开始发牌");
            Thread.sleep(2000);
            for (int i = 0; i < 2; i++) {
                for (int j = 0; j < 2; j++) {
                    players.get(i).puke[j] = pukes.get(0);//每人每次拿第一张牌(每人的两张牌）
                    pukes.remove(0);//每次拿完第一张牌都有新的第一张牌，用remove把索引为0的牌拿去，所有的牌索引加一
                }
                Thread.sleep(2000);
                System.out.println("玩家：" + " " + players.get(i).getName() + " 已拿牌");
            }
            Thread.sleep(2000);
            System.out.println("玩家各自的手牌为：");
            String play_user1cards = players.get(0).puke[0].toString() + "," + players.get(0).puke[1].toString();
            String play_user2cards = players.get(1).puke[0].toString() + "," + players.get(1).puke[1].toString();
            for (Player player : players) {
                Thread.sleep(2000);
                System.out.println(player.getName() + ":" + Arrays.toString(player.puke));
                player.max = Compare.comparePuke(player.puke[0], player.puke[1]);//输出手牌的同时比较出这个人手中的最大牌
                Thread.sleep(2000);
                System.out.println(player.getName() + "的最大手牌为：" + player.max);
            }
            Puke consult = Compare.comparePuke(players.get(0).max, players.get(1).max);//比较出每人的最大手牌哪个更大
            Thread.sleep(2000);
            if (consult.equals(players.get(0).max)) {
                System.out.println(players.get(0).getName() + "获胜");//根据最大手牌决出胜负
                game_winner_ID = players.get(0).getName();
            } else {
                System.out.println(players.get(1).getName() + "获胜");
                game_winner_ID = players.get(1).getName();
            }

            String sql = "insert into record (game_begintime,game_exittime,game_user1ID,game_user2ID,game_winner_ID,game_user1cards,game_user2cards) values (?,?,?,?,?,?,?)";
            PreparedStatement ptmt = conn.prepareStatement(sql);
            Date end_time = new Date();
            Timestamp timestamp2 = new Timestamp(end_time.getTime());
            ptmt.setTimestamp(1, timeStamp1);
            ptmt.setTimestamp(2, timestamp2);
            System.out.println("结束时间：" + timestamp2);
            ptmt.setString(3, LogIn.getUsername());
            ptmt.setString(4, "wang");
            ptmt.setString(5, game_winner_ID);
            ptmt.setString(6, play_user1cards);
            ptmt.setString(7, play_user2cards);
            ptmt.execute();
            System.out.println("游戏结束，您可以选择：按1：退出登录 按任意数字：再来一把");
            Scanner b = new Scanner(System.in);
            int c = b.nextInt();
            if (c == 1) break;
        }
    }
}

class Puke {
    private final String dot;//每张扑克牌的点数
    private final Type type;//每张扑克牌的花色

    //构造方法
    public Puke(String dot, Type type) {
        this.type = type;
        this.dot = dot;
    }

    //重写toString，使其返回点数＋花色
    public String toString() {
        return this.type.getCol() + this.dot;
    }

    public Type getType() {
        return type;
    }

    public String getDot() {
        return dot;
    }
}

class Type {
    private final int num;//花色越大，构造num越大
    private final String col;//花色

    //构造方法
    public Type(String col, int num) {
        this.col = col;
        this.num = num;
    }

    //利用构造方法，越大的花色其对应num越大
    public static Type SPADES = new Type("黑桃", 4);
    public static Type HEARTS = new Type("红桃", 3);
    public static Type CLUBS = new Type("梅花", 2);
    public static Type DIAMOND = new Type("方块", 1);

    public int getNum() {
        return num;
    }

    public String getCol() {
        return col;
    }
}

class Player {
    private final String name;
    public Puke[] puke = new Puke[2];//每个人都会抽两张扑克
    public Puke max;//max为每个人的两张扑克中较大的一个

    public Player(String name) {
        this.name = name;
    }


    public String getName() {
        return name;
    }
}

class Compare {
    //为每张牌的索引规定顺序
    public static List<String> DOTS = List.of("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A");
    public static List<Type> TYPE = List.of(Type.SPADES, Type.HEARTS, Type.CLUBS, Type.DIAMOND);


    public static Puke comparePuke(Puke p1, Puke p2) {
        if (DOTS.indexOf(p1.getDot()) > DOTS.indexOf(p2.getDot())) return p1;//如果扑克牌一对应的contentIndex大于扑克牌二的，返回牌一
        else if (DOTS.indexOf(p1.getDot()) < DOTS.indexOf(p2.getDot())) return p2;
        else if (p1.getType().getNum() > p2.getType().getNum()) return p1;//如果点数相同，返回花色对应num更大的
        else return p2;
    }
}

class LogIn {
    static Scanner input = new Scanner(System.in);
    private static String username;//用户登录注册的姓名
    private static String password;//用户密码
    public static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //用户注册
    public static void zhuce() throws SQLException {
        System.out.println("请输入您的姓名：");
        username = input.next();
        System.out.println("请输入您的登录密码：");
        String p1 = input.next();
        System.out.println("请再次输入您的确认密码：");
        String p2 = input.next();
        Connection conn = DBUtil.getConnection();
        if (p1.equals(p2)) {
            //两次输入的密码相同才可以注册
            password = p1;
            String sql = "insert into user (player_username,player_password,play_createtime) values(?,?,?)";
            PreparedStatement ptmt = conn.prepareStatement(sql);
            ptmt.setString(1, username);
            ptmt.setString(2, password);
            ptmt.setString(3, df.format(new Date()));
            ptmt.execute();
        } else {
            System.out.println("您两次输入密码不相同，请重新注册：");
            zhuce();
        }

    }

    public static String getUsername() {
        return username;
    }

    //用户登录
    public static void denglu() throws SQLException, ParseException {
        System.out.println("请输入你的姓名：");
        username = input.next();
        System.out.println("请输入你的密码：");
        password = input.next();
        Connection conn = DBUtil.getConnection();
        String sql = "select player_username,player_password from user where player_username=? and player_password=?";
        PreparedStatement ptmt = conn.prepareStatement(sql);
        ptmt.setString(1, username);
        ptmt.setString(2, password);
        ResultSet rs = ptmt.executeQuery();
        //从登录用户给出的账号密码来检测查询在数据库表中是否存在相同的账号密码
        if (rs.next()) {
            System.out.println("登录成功！");
            System.out.println("请选择功能：0.直接开始游戏 1.查询用户信息 2.查询某个用户胜率 3.查询某个时间段内的所有游戏记录 4.退出登录");
            int a = input.nextInt();
            if (a == 1) Search.chazhao();
            else if (a == 2) {
                System.out.println("请输入您要查询的用户");
                String user_name = input.next();
                Search.shenglv(user_name);
                System.out.println("请输入任意数以开始游戏");
                input.nextInt();
            } else if (a == 3) {
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println("请输入您要查询的起始时间，格式为yyyy-MM-dd HH:mm:ss");
                Scanner input1 = new Scanner(System.in);
                String start_time = input1.nextLine();
                Date startTime = format.parse(start_time);
                System.out.println("请输入您要查询的截至时间，格式为yyyy-MM-dd HH:mm:ss");
                Scanner input2 = new Scanner(System.in);
                String end_time = input2.nextLine();
                Date endTime = format.parse(end_time);
                String sql0 = "select * from record where game_begintime>=? and game_begintime<=? ";
                Timestamp start = new Timestamp(startTime.getTime());
                Timestamp end = new Timestamp(endTime.getTime());
                PreparedStatement ptmt0 = conn.prepareStatement(sql0);
                ptmt0.setTimestamp(1, start);
                ptmt0.setTimestamp(2, end);
                ResultSet rs0 = ptmt0.executeQuery();
                while (rs0.next()) {
                    System.out.println("游戏ID：" + rs0.getInt("game_ID") + " " + "用户1：" + rs0.getString("game_user1ID") + " " + "用户2" + rs0.getString("game_user2ID") + " " + "获胜者：" + rs0.getString("game_winner_ID") + " " + "用户1手牌：" + rs0.getString("game_user1cards") + " " + "用户2手牌：" + rs0.getString("game_user2cards"));
                }
                System.out.println("输入任意数开始游戏");
                input1.nextInt();
            }
        } else {
            System.out.println("姓名或密码错误！请重新登录：");
            denglu();
        }

    }

    public static void zhuxiao() throws SQLException {
        Connection conn = DBUtil.getConnection();
        System.out.println("请输入您要注销的账户名");
        username = input.next();
        System.out.println("请验证密码");
        password = input.next();
        String sql = "delete from user where player_username=? and player_password=? ";
        PreparedStatement ptmt = conn.prepareStatement(sql);
        ptmt.setString(1, username);
        ptmt.setString(2, password);
        ptmt.execute();
        String sql0 = "select * from user where player_username=? and player_password=? ";
        PreparedStatement ptmt0 = conn.prepareStatement(sql0);
        ptmt0.setString(1, username);
        ptmt0.setString(2, password);
        ptmt0.execute();
        System.out.println("注销成功！");
    }


}

class Search {
    static Scanner input = new Scanner(System.in);
    private static int num;
    private static int counts;

    public static void chazhao() throws SQLException, ParseException {
        Connection conn = DBUtil.getConnection();
        System.out.println("请输入您要查找的用户名");
        //用户登录注册的姓名
        String username = input.next();
        String sql = " select * from user where player_username=? ";
        PreparedStatement ptmt = conn.prepareStatement(sql);
        ptmt.setString(1, username);
        ResultSet rs = ptmt.executeQuery();
        if (rs.next()) {
            System.out.println("查找成功");
            System.out.println("用户名：" + rs.getString("player_username") + " " + "创建日期：" + rs.getDate("play_createtime").toString());
            System.out.println("按任意键开始游戏");
            input.next();
        } else {
            System.out.println("查找失败，请重试");
            chazhao();
        }
    }

    public static void shenglv(String user_name) throws SQLException {
        Connection conn = DBUtil.getConnection();
        String sql1 = "SELECT COUNT(*) num FROM record WHERE game_winner_ID=? ";
        PreparedStatement ptmt = conn.prepareStatement(sql1);
        ptmt.setString(1, user_name);
        ResultSet rs1 = ptmt.executeQuery();
        while (rs1.next()) {
            num = rs1.getInt("num");
        }
        String sql2 = "select count(*) counts from record";
        Statement st = conn.createStatement();
        ResultSet rs2 = st.executeQuery(sql2);
        while (rs2.next()) {
            counts = rs2.getInt("counts");
        }
        float shenglv = (float) num / (float) counts;
        System.out.println("该用户胜率为" + 100 * shenglv + "%");
    }

}
